import { GlobalStore } from '@/stores';
import { boot } from 'quasar/wrappers';
import storage from 'store';
import { Router } from 'vue-router';
import UserForm from '@/pages/tsystem/UserForm/index.vue';
import NProgress from 'nprogress';
import '@/css/nprogress.css';
NProgress.configure({ showSpinner: false });
// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)

const whiteList = ['/login'];
const globalStore = GlobalStore();

// const ruleList = [
//   {
//     view_path: '/tsystem/PowerForm',
//     name: '/tsystem/PowerForm',
//   },
//   {
//     view_path: '/tsystem/UserForm',
//     name: '/tsystem/UserForm',
//   },
//   {
//     view_path: '/tsystem/BasicRole',
//     name: '/tsystem/BasicRole',
//     meta: {
//       title: '角色管理',
//     },
//   },
// ];

async function pushRouter(router: Router): Promise<void> {
  return new Promise((reslove, reject) => {
    setTimeout(() => {
      console.log(
        'globalStore',
        globalStore.accountId,
        globalStore.userInfo,
        globalStore.token
      );
      const ruleList = globalStore.userInfo.ruleList;
      // console.log(router.hasRoute('Layout'));
      ruleList.forEach((navigation: any) => {
        router.addRoute('Layout', {
          path: navigation.view_path,
          meta: { name: navigation.name },
          name: navigation.name,
          component: () =>
            import(
              /* @vite-ignore */ `../pages${navigation.view_path}/index.vue`
            ),
        });
      });
      // router.addRoute('Layout', ruleList[0]);
      reslove();
    }, 20);
  });
}

export default boot(({ router }) => {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const token = storage.get('Access-Token');
    if (token) {
      if (to.path === '/login') {
        NProgress.done();
        return next('/');
      }

      // ruleList.forEach((navigation) => {});
      if (globalStore.accountId === 0) {
        await pushRouter(router);
        globalStore.accountId = 1;
        console.log(router.getRoutes(), '查看现有路由');
        next({ ...to, replace: true }); //路由进行重定向放行
        NProgress.done();
      } else {
        next();
        NProgress.done();
      }
    } else {
      if (whiteList.includes(to.path)) {
        next();
      } else {
        next('/login');
      }
      NProgress.done();
    }

    // next();
  });
  router.afterEach(() => {
    NProgress.done(); // finish progress bar
  });
});
